package cn.rwklyd.BookKeeping.service;

import cn.rwklyd.BookKeeping.exception.BaseException;
import cn.rwklyd.BookKeeping.handler.LoginFailureHandler;
import cn.rwklyd.BookKeeping.mapper.PermissionMapper;
import cn.rwklyd.BookKeeping.mapper.UserMapper;
import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.pojo.Permission;
import cn.rwklyd.BookKeeping.pojo.User;
import cn.rwklyd.BookKeeping.pojo.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

// 重写Security的UserDetailsService,将内存查询改造成数据库查询
@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userRepository;
    @Autowired
    private PermissionMapper permissionRepository;
    @Autowired private LoginFailureHandler loginFailureHandler;

    // 重写loadUserByUsername方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.getUserByUsername(username);
        log.info("用户信息:{}", user);
        if (user == null) {
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
            //  throw new UsernameNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 检查用户状态
        if (user.getStatus() == User.UserStatus.locked) {
            throw new BaseException(MessageConstant.ACCOUNT_LOCKED);
            //  throw new LockedException("账号被锁定");
        }
        // 查询用户权限列表
        List<Permission> permissions = permissionRepository.getPermissionsByRoleId(user.getRoleId());


        // 第四步：将登录对象信息和权限信息封装到LoginUser中
        return new LoginUser(user, permissions);
    }
}